package com.star.rpc;

import com.star.rpc.config.RegistryConfig;
import com.star.rpc.config.RpcConfig;
import com.star.rpc.constant.RpcConstant;
import com.star.rpc.registry.Registry;
import com.star.rpc.registry.RegistryFactory;
import com.star.rpc.utils.ConfigUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * packageName com.star.rpc
 *
 * @author zerostart
 * @className RpcApplication
 * @date 2024/11/19
 * @description  RPC框架应用，存放了项目用到的全局变量，双检索实现
 */



@Slf4j
public class RpcApplication {
    private static volatile RpcConfig rpcConfig;

    public static void init(RpcConfig newRpcConfig) {
        rpcConfig = newRpcConfig;
        log.info("rpc init, config = {}", new RpcConfig());
        //注册中心初始化
        RegistryConfig registryConfig = new RegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        registry.init(registryConfig);

        log.info("registry init config = {}", registryConfig);

        //创建并注册shutdown hook,
        Runtime.getRuntime().addShutdownHook(new Thread(registry::destroy));
    }

    public static void init() {
        RpcConfig newRpcConfig;

        try {
            newRpcConfig = ConfigUtils.loadConfig(RpcConfig.class, RpcConstant.DEFAULT_CONFIG_PREFIX);
        } catch (Exception e) {
            // 配置加载失败，使用默认值
            newRpcConfig = new RpcConfig();
        }
        init(newRpcConfig);
    }

    /**
     * 获取配置
     */
    public static RpcConfig getRpcConfig() {
        if (rpcConfig == null) {
            synchronized (RpcApplication.class) {
                if (rpcConfig == null)
                    init();
            }

        }
        return rpcConfig;
    }
}
